<template>
    <div>
        <!-- 搜索栏 -->
        <el-form :inline="true" :model="queryInfo">
            <el-form-item label="姓名">
                <el-input v-model="queryInfo.name" placeholder="请输入搜索姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="电话">
                <el-input v-model="queryInfo.phone" placeholder="请输入电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="">
                <el-select v-model="queryInfo.status" placeholder="全部" clearable>
                    <el-option label="启用" value="0"></el-option>
                    <el-option label="禁用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getUserList">查询</el-button>
                <el-button type="success" @click="handleAdd">添加</el-button>
                <el-button type="danger" @click="deleteBatch">批量删除</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="users" border stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号" width="70"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="phone" label="电话"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 30, 50]" :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <!-- 新增用户对话框 -->
        <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="handleClose" :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" ref="ruleForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" autocomplete="off" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="form.phone" autocomplete="off" placeholder="请输入电话"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="form.address" autocomplete="off" placeholder="请输入地址"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser" v-show="title == '添加用户'">确 定</el-button>
                <el-button type="primary" @click="updateUser" v-show="title == '修改用户'">确 定</el-button>
            </div>
        </el-dialog>

    </div>

</template>

<script>
export default {
    data() {
        return {
            queryInfo: {
                name: '',
                phone: '',
                status: null,
                pageNum: 1,
                pageSize: 5
            },
            users: [],
            total: 0, // 总条数
            dialogFormVisible: false, // 控制模态框显示或隐藏
            form: {

            },
            rules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                phone: [
                    { pattern: /^1\d{10}$/, message: '手机号格式不正确', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' },
                ],
            },
            title: '添加用户',
            multipleSelection: [] // 复选框的选中项
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        // 获取用户列表
        async getUserList() {
            const { data: res } = await this.$http.get('/users/queryByPage', {
                params: this.queryInfo
            })
            this.users = res.data.records
            this.users.forEach(item => {
                item.status = item.status === 0
            })
            this.total = res.data.total
        },
        handleSizeChange(val) {
            this.queryInfo.pageSize = val
            this.getUserList()
        },
        handleCurrentChange(val) {
            this.queryInfo.pageNum = val
            this.getUserList()
        },
        // 删除
        handleDelete(id) {
            this.$confirm('确定要删除该用户吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`/users/remove/${id}`)
                if (res.status === 200) {
                    this.$message.success('删除成功！')
                } else {
                    this.$message.error('删除失败！')
                }
            }).catch(() => {
                this.$message.info('取消删除');
            });
        },
        // 添加用户
        addUser() {
            this.$refs.ruleForm.validate(async valid => {
                if (valid) {
                    const { data: res } = await this.$http.post('/users/add', this.form)
                    if (res.status === 200) {
                        this.$message.success('添加成功！')
                        this.dialogFormVisible = false
                        this.getUserList()
                    } else {
                        this.$message.error(res.msg)
                    }
                }
            })
        },
        // 监听对话框的关闭事件
        handleClose() {
            this.form = {}
            this.$refs.ruleForm.resetFields() // 重置表单
        },
        // 打开添加对话框
        handleAdd() {
            this.title = '添加用户'
            this.dialogFormVisible = true
        },
        // 打开编辑对话框 
        async handleEdit(id) {
            this.title = '修改用户'

            const { data: res } = await this.$http.get('/users/query/' + id)
            this.form = res.data

            this.dialogFormVisible = true
        },
        updateUser() {
            this.$refs.ruleForm.validate(async valid => {
                if (valid) {
                    const { data: res } = await this.$http.put('/users/modify', this.form)
                    if (res.status === 200) {
                        this.$message.success('修改成功！')
                        this.dialogFormVisible = false
                        this.getUserList()
                    } else {
                        this.$message.error(res.msg)
                    }
                }
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 批量删除
        deleteBatch(){
            // var ids = []
            // this.multipleSelection.forEach(item => {
            //     ids.push(item.id)
            // })
            var ids = this.multipleSelection.map(item => item.id)
        }
    }
}
</script>

<style lang="less" scoped>
.el-pagination {
    text-align: center;
    margin-top: 5px;
}
</style>